/*
 * =====================================================================================
 *
 *       Filename:  fcgi_main.cc
 *
 *    Description:  
 *
 *        Version:  1.0
 *        Created:  2013年07月03日 18时43分01秒
 *       Revision:  none
 *       Compiler:  gcc
 *
 *         Author:  Xie Yanping (), 
 *        Company:  www.Qihoo.net
 *
 * =====================================================================================
 */

#include "base/logging.h"
#include "base/config_reader.h"

#include "logs_search_request.h"
#include "broadcast_message_request.h"

#include "fcgi_service/fcgi_service.h"
using namespace fcgi;

namespace imserver {
namespace fcgi {

class ImRequestFactory : public RequestFactory {
public:
  virtual RequestPtr Create(FCGX_Request * r) {
    char * path = FCGX_GetParam("SCRIPT_NAME", r->envp);
    RequestPtr req;
    if (path) {
      if (strcmp(path, "/logs/search") == 0) {
        req = RequestPtr(new LogsSearchRequest(r));
      } else if(strcmp(path, "logs/broadcast")) {
        req = RequestPtr(new BroadcastMessageRequest(r));
      }
    }
    return req;
  }
};

}
}


int main(int argc, char **argv) {
  char * conf_file = "../conf/log_search_service.conf";
  char opt;
  while ((opt = getopt(argc, argv, "c:")) != -1) {
    switch (opt) {
    case 'c':
      conf_file = optarg;
      break;
    default:
      std::cerr << "Unknown option " << optopt << std::endl;
      return 1;
    }
  }

  ConfigReader cfg(conf_file);
  if (!cfg) {
    std::cerr << "Config file " << conf_file << " read error!" << std::endl;
    return 1;
  }

  LOG_INIT(cfg.Get("log4cplus", "file"), cfg.Get("log4cplus", "level"));
  // FcgiServer * fcgi_server = new FcgiServer("127.0.0.1:19000", 128);

  std::string bind_addr = cfg.Get("im_rest_service", "bind");

  LOG_INFO("listens on port " << bind_addr);

  FcgiServer * fcgi_server = new FcgiServer(bind_addr, 128);
  fcgi_server->RegisterRequestFactory(RequestFactoryPtr(new imserver::fcgi::ImRequestFactory()));
  fcgi_server->Start(true); // 本线程也处理 fcgi 请求，不退出
  return 0;
}

